import express from 'express';
import fs from 'fs';
import path from 'path';
import { DatabaseProjectService } from '../services/DatabaseProjectService.js';
import { PathMappingService } from '../services/PathMappingService.js';

const router = express.Router();

/**
 * 获取所有项目
 */
router.get('/', async (req, res) => {
  try {
    // 添加缓存控制头
    res.set({
      'Cache-Control': 'no-cache, no-store, must-revalidate',
      'Pragma': 'no-cache',
      'Expires': '0'
    });
    
    const projects = await DatabaseProjectService.getAllProjects();
    res.json({ success: true, data: projects });
  } catch (error: any) {
    res.status(500).json({ 
      success: false, 
      error: `获取项目列表失败: ${error.message}` 
    });
  }
});

/**
 * 添加新项目
 */
router.post('/', async (req, res) => {
  try {
    const { name, path: projectPath, description } = req.body;

    if (!name || !projectPath) {
      return res.status(400).json({ 
        success: false, 
        error: '项目名称和路径不能为空' 
      });
    }

    // 验证路径格式和存在性
    if (!projectPath || typeof projectPath !== 'string') {
      return res.status(400).json({ 
        success: false, 
        error: '项目路径格式无效' 
      });
    }

    // 检查是否为浏览器选择的目录格式
    if (projectPath.includes('(浏览器选择的目录)')) {
      return res.status(400).json({ 
        success: false, 
        error: '请输入完整的文件系统路径，而不是浏览器显示的目录名。例如：C:\\Users\\YourName\\Projects\\ProjectName' 
      });
    }

    // Docker环境路径映射
    const mappedPath = PathMappingService.mapHostPathToContainer(projectPath);
    const pathMappingInfo = PathMappingService.getPathMappingSuggestion(projectPath);
    
    console.log(`[Projects] 原始路径: ${projectPath}`);
    console.log(`[Projects] 映射路径: ${mappedPath}`);
    console.log(`[Projects] 路径有效: ${pathMappingInfo.isValid}`);

    // 验证映射后的路径是否存在
    if (!fs.existsSync(mappedPath)) {
      let errorMessage = `指定的项目路径不存在: ${projectPath}`;
      
      if (PathMappingService.isRunningInDocker()) {
        errorMessage += `\n映射路径: ${mappedPath}`;
        if (pathMappingInfo.suggestion) {
          errorMessage += `\n\n建议: ${pathMappingInfo.suggestion}`;
        }
      }
      
      return res.status(400).json({ 
        success: false, 
        error: errorMessage
      });
    }

    // 验证是否为Git仓库
    const gitDir = path.join(mappedPath, '.git');
    if (!fs.existsSync(gitDir)) {
      return res.status(400).json({ 
        success: false, 
        error: `指定路径不是有效的Git仓库: ${mappedPath}\n请确保该目录包含.git文件夹` 
      });
    }

    // 检查项目是否已存在（按路径）
  const existingProjects = await DatabaseProjectService.getAllProjects();
  const existingProject = existingProjects.find(p => p.path === projectPath);
  
  if (existingProject) {
    return res.status(400).json({
      success: false,
      error: `项目路径已存在: ${existingProject.name} (${existingProject.path})`
    });
  }

    // 创建新项目（存储原始路径，运行时会自动映射）
    const newProject = await DatabaseProjectService.addProject({
      name,
      path: projectPath, // 存储原始宿主机路径
      description: description || ''
    });
    
    // 添加Docker环境信息到响应
    const dockerInfo = PathMappingService.getDockerInfo();
    const responseData = {
      ...newProject,
      dockerInfo: dockerInfo.isDocker ? {
        isDocker: true,
        originalPath: projectPath,
        mappedPath: mappedPath,
        projectRoot: dockerInfo.projectRoot
      } : undefined
    };

    res.json({ success: true, data: responseData });
  } catch (error: any) {
    res.status(500).json({ 
      success: false, 
      error: `添加项目失败: ${error.message}` 
    });
  }
});

/**
 * 删除项目
 */
router.delete('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    const projects = await DatabaseProjectService.getAllProjects();
    const project = projects.find(p => p.id === id);
    if (!project) {
      return res.status(404).json({ 
        success: false, 
        error: '项目不存在' 
      });
    }

    await DatabaseProjectService.deleteProject(id);

    res.json({ success: true, message: '项目删除成功' });
  } catch (error: any) {
    res.status(500).json({ 
      success: false, 
      error: `删除项目失败: ${error.message}` 
    });
  }
});

/**
 * 获取项目作者列表
 */
router.post('/:id/authors', async (req, res) => {
  try {
    const { id } = req.params;
    
    const projects = await DatabaseProjectService.getAllProjects();
    const project = projects.find(p => p.id === id);
    if (!project) {
      return res.status(404).json({ 
        success: false, 
        error: '项目不存在' 
      });
    }

    // 使用git命令获取作者列表
    const { execAsync } = await import('../utils/execAsync');
    const { stdout } = await execAsync('git log --format="%an" | sort | uniq', {
      cwd: project.path,
      maxBuffer: 1024 * 1024
    });
    
    const authors = stdout.trim().split('\n').filter(author => author.trim());
    res.json({ success: true, data: authors });
  } catch (error: any) {
    res.status(500).json({ 
      success: false, 
      error: `获取项目作者失败: ${error.message}` 
    });
  }
});

/**
 * 获取项目总提交数
 */
router.post('/:id/commits/count', async (req, res) => {
  try {
    const { id } = req.params;
    
    const projects = await DatabaseProjectService.getAllProjects();
    const project = projects.find(p => p.id === id);
    if (!project) {
      return res.status(404).json({ 
        success: false, 
        error: '项目不存在' 
      });
    }

    // 使用git命令获取提交数
    const { execAsync } = await import('../utils/execAsync');
    const { stdout } = await execAsync('git rev-list --count HEAD', {
      cwd: project.path
    });
    
    const count = parseInt(stdout.trim()) || 0;
    res.json({ success: true, data: count });
  } catch (error: any) {
    res.status(500).json({ 
      success: false, 
      error: `获取项目提交数失败: ${error.message}` 
    });
  }
});

export default router;